import time
import os
from selenium import webdriver
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
import datetime
from email.header import Header

nowtime = datetime.datetime.now().strftime('%m-%d')#获取当前时间
print(nowtime)
print('\n','***Write By 盛意以山河***','\n')
#环境配置
chromedriver = "C:\\Program Files (x86)\\Google\Chrome\\Application"
os.environ["webdriver.ie.driver"] = chromedriver
def bao():
    #从文件中读取用户名和密码，账号密码qq在同一行，每次都要换行
    f = open('D:\\username.txt','r')
    username = list(f)
    f.close#杜账号
    print(username)
    f = open('D:\\password.txt','r')
    password = list(f)
    f.close#杜密码
    print(password)
    f = open('D:\\qq.txt','r')
    user_email = list(f)    
    f.close#杜邮箱
    print(user_email)
    finsh = 0
    sum = len(username)
    print('账号密码读取成功，共',sum,'人')

    #打开浏览器
    driver=webdriver.Chrome() 
    driver.get('http://yiqing.ctgu.edu.cn/wx/health/main.do')

    #尝试报平安
    try:
        for x in range(sum):
            
            driver.find_element_by_id('username1').click() #点击用户名输入框
            driver.find_element_by_id('username1').clear() #清空输入框
            time.sleep(1)
            driver.find_element_by_id('username1').send_keys(username[x]) #自动敲入用户名
            
            driver.find_element_by_id('password1').click() #点击密码输入框
            driver.find_element_by_id('password1').clear() #清空输入框
            # time.sleep(1)
            driver.find_element_by_id('password1').send_keys(password[x]) #自动敲入密码
            # driver.find_element_by_xpath('/html/body/main/section[2]/form/div[3]/input').click() #点击登陆
            time.sleep(2)
            #判断是是否密码错误
            try:
                state0 = driver.find_element_by_id('msg').text
                if len(state0) != 0:
                    print('用户',username[x]+'密码错误，请检查该用户密码后重试!')
                    continue
            except:
                pass
            #班委不一样,先切换角色
            s = driver.find_elements_by_id('menu_wjdc')
            if len(s) != 0:
                print('该用户是班委')
                driver.find_element_by_id('menu_my').click() #点击我的按钮
                time.sleep(1)                
                driver.find_element_by_id('change_btn').click()#点击切换角色
                time.sleep(1)
                driver.find_element_by_xpath('/html/body/main/div[2]/section/form/div/div/div/div/label[2]').click()#点击学生
                driver.find_element_by_xpath('/html/body/main/div[2]/div/button').click()#点击确定
                time.sleep(5)  
            else:
                pass
            driver.find_element_by_xpath('/html/body/main/section/header/div[2]/button').click() #点击报平安
            # 尝试保平安，因为可能已经报过了
            try:
                driver.find_element_by_xpath('/html/body/main/div[1]/button').click()#点击报平安
                time.sleep(2)
                driver.find_element_by_xpath('/html/body/div[2]/div[3]/a[2]').click() #点击提交
                time.sleep(3)
                if user_email[x] != '\n':#判断有没有填邮箱          
                    driver.get_screenshot_as_file(u"baopingan.png")#保存截图
                    driver.quit
                    send(user_email[x].strip('\n')+'@qq.com')#发邮件通知每个人
                    print('用户'+username[x].strip('\n')+'的邮箱'+user_email[x].strip('\n')+'发送成功')
                    time.sleep(1)
                else:
                    print('用户'+username[x].strip('\n')+'未填写邮箱，未发送邮件')
            except:
                print('')
            time.sleep(2)
            state1 = driver.find_element_by_xpath('/html/body/main/section/header/div[1]/span').text #判断是否报成功
            state2 = driver.find_element_by_xpath('/html/body/main/section/header/div[1]').text #获取真实名字
            if state1 == '今日已上报':
                print('用户',username[x]+state2)
                print('\n')
                finsh = finsh + 1
            else:
                print('用户',username[x],'报平安失败，请重新上报')
            driver.find_element_by_id('menu_my').click() #点击我的按钮
            time.sleep(2)
            driver.find_element_by_id('submit_btn').click() #点击退出登录
            time.sleep(1)
        print('\n','应报',sum,'人','实报',finsh,'人','请查收！')
    #不管有没成功，都发邮件
    finally:
        if sum == finsh:
            msg = '应报'+str(sum)+'人'+'实报'+str(finsh)+'人'+'请查收！'
            head = '安全上报成功'
        else:
            msg = '应报'+str(sum)+'人'+'实报'+str(finsh)+'人'+'请检查服务器！'
            head = '安全上报失败'
                
        send_rusult(head,msg)#发邮件给作者反馈结果
        driver.close()
    return msg,head

def send(to_addr,):
    # 发信方的信息：发信邮箱，邮箱授权码
    from_addr = '邮箱'
    password = '授权码填在这'
    
    # 收信方邮箱
    # to_addr = '2454398382@qq.com'
    subject = nowtime+"安全上报已成功！"  # 主题
    msg = MIMEMultipart('related')
    content = MIMEText('<html><body><img src="cid:imageid" alt="imageid"></body></html>', 'html', 'utf-8')  # 正文
    # msg = MIMEText(content)
    msg.attach(content)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
 
    file = open("baopingan.png", "rb")
    img_data = file.read()
    file.close()
 
    img = MIMEImage(img_data)
    img.add_header('Content-ID', 'imageid')
    msg.attach(img)
 
    # try:
    s = smtplib.SMTP_SSL("smtp.163.com",994)  # 邮件服务器及端口号
    s.login(from_addr, password)
    s.sendmail(from_addr, to_addr, msg.as_string())
    s.quit()

# 这个应该是可以和上面合并的，写的多余了
def send_rusult(head,text):
    msg_from=''#发送方邮箱
    passwd='' #填入发送方邮箱的授权码
    msg_to='' #收件人邮箱
                                
    subject= head#主题     
    content= text
    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = msg_from
    msg['To'] = msg_to

    s = smtplib.SMTP_SSL("smtp.163.com",994)
    s.login(msg_from, passwd)
    s.sendmail(msg_from, msg_to, msg.as_string())
    print ("发送结果成功")
    s.quit()

def main():
    bao()

if __name__ == "__main__":
    main()

